/** 
 * Copyright (C) 2018 Jeebiz (http://jeebiz.net).
 * All Rights Reserved. 
 */
package net.jeebiz.cloud.authz.facex.setup.provider;

import java.util.Base64;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.arcsoft.face.spring.boot.ArcFaceRecognitionTemplate;
import com.arcsoft.face.spring.boot.FaceLiveness;

import net.jeebiz.cloud.api.exception.BizRuntimeException;
import net.jeebiz.cloud.authz.facex.dao.IAuthzFaceDao;
import net.jeebiz.cloud.authz.facex.dao.IAuthzFaceRepositoryDao;
import net.jeebiz.cloud.authz.facex.dao.entities.AuthzFaceModel;

@Component
public class ArcFaceRecognitionProvider implements FaceRecognitionProvider {

	@Autowired
	private ArcFaceRecognitionTemplate faceRecognitionTemplate;
	@Autowired
	private IAuthzFaceDao authzFace;
	@Autowired
	private IAuthzFaceRepositoryDao authzFaceRepository;
	
	@Override
	public String getName() {
		return "arcface";
	}

	@Override
	public JSONObject detect(byte[] imageBytes, String filename) throws Exception {
		return getFaceRecognitionTemplate().detect(imageBytes);
	}

	@Override
	public JSONObject verify(MultipartFile image) throws Exception {
		return getFaceRecognitionTemplate().verify(image.getBytes(), FaceLiveness.LOW);
	}

	@Override
	public JSONObject match(String userId, MultipartFile image) throws Exception {
		AuthzFaceModel model = getAuthzFace().getModel(userId);
		return getFaceRecognitionTemplate().match(image.getBytes(), Base64.getDecoder().decode(model.getFace()),  FaceLiveness.LOW);
	}

	@Override
	public JSONObject search(MultipartFile image) throws Exception {
		throw new BizRuntimeException("not support");
	}

	@Override
	public JSONObject merge(MultipartFile template, MultipartFile target) throws Exception {
		throw new BizRuntimeException("not support");
	}
	
	public ArcFaceRecognitionTemplate getFaceRecognitionTemplate() {
		return faceRecognitionTemplate;
	}

	public IAuthzFaceDao getAuthzFace() {
		return authzFace;
	}

	public IAuthzFaceRepositoryDao getAuthzFaceRepository() {
		return authzFaceRepository;
	}

}
